package com.dj.common.web.service.impl;

import java.util.Iterator;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;

import com.dj.common.web.vo.PageAndSortVo;
import com.dj.common.web.vo.PageData;

public class BaseCrudServiceImpl<V> {


	public PageAndSortVo<V> convertToPageAndSortVo(Pageable pageRequest,
			V vo, boolean isCount) {
		PageAndSortVo<V> pageVo = new PageAndSortVo<>();
		if (null != pageRequest) {
			pageVo.setOffset(pageRequest.getOffset());
			pageVo.setLimit(pageRequest.getPageSize());
			pageVo.setSort(getSort(pageRequest.getSort()));
			pageVo.setCount(isCount);
		} else {
			pageVo.setOffset(0);
			pageVo.setLimit(0);
		}
		if(null!=vo){
			/*if(null!=vo.get(PageAndSortVo.SUM_PD_NAME)){
				pageVo.setPd((PageData)vo.get(PageAndSortVo.SUM_PD_NAME));
			}*/
		}
		pageVo.setVo(vo);
		return pageVo;

	}
	/**
	 * 组装排序的字段
	 * 
	 * @param sort
	 * @return
	 */
	protected String getSort(Sort sort) {
		if (sort == null)
			return null;

		Iterator<Order> iterator = sort.iterator();
		String orderBySql = "";
		while (iterator.hasNext()) {
			Order order = iterator.next();
			String fieldName = order.getProperty();
			String sortDirection = order.getDirection().name();
			orderBySql += fieldName + " " + sortDirection + ",";
		}
		return orderBySql.substring(0, orderBySql.length() - 1);
	}
}
